use std::ops::Deref;

use crate::{JEnv, JObject, JVm};

pub struct JRc<T: AsRef<JObject> + 'static> {
	inner: &'static T,
}
impl<T: AsRef<JObject> + 'static> Drop for JRc<T> {
	fn drop(&mut self) {
		JVm::singleton(None).unwrap().env().unwrap().del_global(self.inner.as_ref())
	}
}
impl<T: AsRef<JObject>> JRc<T> {
	pub(crate) fn try_from(value: sys::jobject) -> Result<Self, ()> {
		if !value.is_null() {
			Ok(Self {
				inner: unsafe { &*(value as *mut T) },
			})
		} else {
			Err(())
		}
	}
	pub fn clone(&self, env: &JEnv) -> Option<JRc<T>> {
		env.new_global(self.inner)
	}
}

impl<T: AsRef<JObject>> Deref for JRc<T> {
	type Target = T;
	fn deref(&self) -> &Self::Target {
		self.inner
	}
}
